package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/websocket"
)

func main() {

	//连接方式http://127.0.0.1:8000/http
	http.HandleFunc("/http", myHandler)
	//连接格式为 ws://IP或域名:端口  后面有可能要加上路由信息
	//ws://127.0.0.1:8000/ws
	http.HandleFunc("/ws", myHandlerWs)
	//一个普普通通的http服务，可以支持http请求和websocket请求
	http.ListenAndServe("127.0.0.1:8000", nil)
}

// handler函数
func myHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.RemoteAddr, "连接成功")
	// 请求方式：GET POST DELETE PUT UPDATE
	fmt.Println("method:", r.Method)
	// /go
	fmt.Println("url:", r.URL.Path)
	fmt.Println("header:", r.Header)
	fmt.Println("收到的body:", r.Body)
	// 回复
	w.Write([]byte("这是一个普通的http请求"))

}

var wu = &websocket.Upgrader{ReadBufferSize: 2,
	WriteBufferSize: 512, CheckOrigin: func(r *http.Request) bool { return true }}

//将一次http请求升级为websocket
func myHandlerWs(w http.ResponseWriter, r *http.Request) {
	conn, _ := wu.Upgrade(w, r, nil)
	fmt.Println("收到的body:", r.Body)

	go func(conn *websocket.Conn) {
		defer conn.Close()
		for {
			//读取ws中的数据
			mType, msg, err := conn.ReadMessage()
			if err != nil { //客户端退出
				fmt.Println("客户端退出")
				break
			}
			fmt.Println("---", mType, string(msg))
			//写入数据
			// conn.WriteMessage(mType, msg)
		}
	}(conn)
	fmt.Println("每次http请求就会升级为websocket")
	w.Write([]byte("这是一个普通的ws请求"))
}
